<template>
	<div class="layout-padding">
		<splitpanes>
			<pane size="20">
				<div class="layout-padding-auto layout-padding-view">
					<el-input prefix-icon="search" v-model="filterText" placeholder="请输入关键字搜索" class="mb-2" />
					<el-scrollbar>
						<el-tree
							ref="treeRef"
							:data="treeData.list"
							:props="treeData.defaultProps"
							@node-click="handleNodeClick"
							node-key="id"
							:default-expand-all="true"
							:highlight-current="true"
							:expand-on-click-node="false"
							:filter-node-method="filterNode"
						/>
					</el-scrollbar>
				</div>
			</pane>
			<pane class="ml8">
				<div class="layout-padding-auto layout-padding-view">
					<el-row>
						<el-form :model="form" ref="dataFormRef" :inline="true" @keyup.enter="getDataList" :rules="dataRules" v-loading="loading">
							<el-form-item label="数据类型" prop="form.range" class="w-[150px]">
								<el-select placeholder="请选择设备" v-model="form.range" size="small">
									<el-option v-for="item in sourceRangeTime" :key="item.name" :value="item.name" :label="item.label" />
								</el-select>
							</el-form-item>
							<el-form-item prop="dateTime" label="时间" class="w-[280px]">
								<el-date-picker
									size="small"
									v-model="form.dateTime"
									type="daterange"
									start-placeholder="开始时间"
									end-placeholder="结束时间"
									value-format="YYYY-MM-DD"
								/>
							</el-form-item>
							<el-form-item prop="deviceIds" label="设备">
								<el-select
									placeholder="请选择设备"
									v-model="form.deviceIds"
									size="small"
									filterable
									multiple
									:collapse-tags-tooltip="true"
									:collapse-tags="true"
									:multiple-limit="4"
								>
									<el-option v-for="item in deviceList" :key="item.id" :value="item.id" :label="item.name" />
								</el-select>
							</el-form-item>

							<el-form-item>
								<el-button icon="search" type="primary" class="ml-2" size="small" @click="getDataList">查询</el-button>
							</el-form-item>
						</el-form>
					</el-row>
					<div class="h-[calc(100%-60px)] overflow-y-auto">
						<div v-for="(item, index) in chartData.list" :key="index" class="mb-4">
							<el-card shadow="never" size="small">
								<template #header>
									<div class="font-semibold text-primary">{{ item.name }}</div>
								</template>
								<div class="flex h-[240px] w-full">
									<div class="flex-1 w-full h-full">
										<PieChart :data="item.pollutionList" name="监测因子占比" title="监测因子占比" radius="60%" :center="['50%', '58%']" />
									</div>
									<div class="flex-1 w-full h-full">
										<PieChart :data="item.divisorList" name="污染物占比" title="污染物占比" radius="60%" :center="['50%', '58%']" />
									</div>
								</div>
							</el-card>
						</div>
						<div v-if="!chartData.list.length" class="pt-6">
							<el-empty :image-size="80" description="暂无数据" />
						</div>
					</div>
				</div>
			</pane>
		</splitpanes>
	</div>
</template>

<script setup lang="ts" name="pollutionSource">
import { fetchList } from '/@/api/platform/pollutionSource';
import { fetchAreaList as fetchTreeList } from '/@/api/platform/codeArea';
import { fetchListByTag } from '/@/api/platform/airMonitorEquipment';
import { handleTree } from '/@/utils/other';
import { formatSourceData, sourceRangeTime, ChartsDataType } from './data';
import { formatDate } from '/@/utils/formatTime';
import { useMessage } from '/@/hooks/message';
type Tree = {
	[key: string]: any;
};
type optionType = {
	id: string;
	name: string;
};
const PieChart = defineAsyncComponent(() => import('/@/components/Echarts/pie.vue'));
// 定义变量内容
const dataFormRef = ref();
const deviceList = ref<optionType[]>([]);
const chartData = reactive<{ list: { divisorList: ChartsDataType[]; pollutionList: ChartsDataType[]; name: string }[] }>({ list: [] });
const siteId = ref();
const filterText = ref('');
const treeRef = ref();
const loading = ref(false);
const form = reactive({
	range: sourceRangeTime[0].name,
	deviceIds: [],
	dateTime: [formatDate(new Date(new Date().getTime() - 3600 * 1000 * 24 * 7), 'YYYY-mm-dd'), formatDate(new Date(), 'YYYY-mm-dd')],
});
// 定义校验规则
const dataRules = ref({
	range: [{ required: true, message: '请选择', trigger: 'change' }],
	deviceIds: [{ required: true, message: '请选择', trigger: 'change' }],
	dateTime: [{ required: true, message: '请选择', trigger: 'change' }],
});
// 区域树使用的数据
const treeData = reactive({
	list: [],
	defaultProps: {
		label: 'name',
	},
});
// 树节点查找设备
const getDeviceList = () => {
	fetchListByTag({ tag: unref(siteId) }).then((res) => {
		deviceList.value = res.data;
		form.deviceIds = [];
	});
};
// 点击树
const handleNodeClick = (e: any) => {
	siteId.value = e.id;
	getDeviceList();
};

// 搜索树监听
watch(filterText, (val) => {
	treeRef.value!.filter(val);
});
const getTreeDate = async () => {
	await fetchTreeList().then((res: any) => {
		const records = res.data;
		if (records.length) {
			treeData.list = handleTree(records, 'id', 'pid', 'children', '1111111111111111111');
			siteId.value = treeData.list[0]?.id;
			getDeviceList();
			nextTick(() => {
				unref(treeRef)?.setCurrentKey(siteId.value, true);
			});
		}
	});
};
const filterNode = (value: string, data: Tree) => {
	if (!value) return true;
	return data.name.includes(value);
};
const getDataList = async () => {
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return false;
	if (form.range === 'RealTime') {
		const date1 = new Date(form.dateTime[0]).getTime();
		const date2 = new Date(form.dateTime[1]).getTime();
		const d_range = 1000 * 60 * 60 * 24 * 7;
		if (date2 - date1 > d_range) {
			useMessage().wraning('实时数据选择时间范围不可大于7天！');
			return false;
		}
	}
	try {
		loading.value = true;
		const res = await fetchList({ dt0: form.dateTime[0], dt1: form.dateTime[1], tp: form.range, monitorEquipmentIds: form.deviceIds });
		chartData.list = [];
		for (let i = 0; i < res.data.length; i++) {
			const { divisorList, pollutionList } = formatSourceData(res.data[i]);
			chartData.list.push({ divisorList, pollutionList, name: res.data[i].equipmentName });
		}
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};
onMounted(() => {
	getTreeDate();
});
</script>

<style lang="scss" scoped>
:deep(.el-card__header) {
	padding: 12px 20px;
}
</style>
